
const db = require('../db');

exports.getUserInfo = (req, res) => {
    let userId = req.body.id;

    let sql = `SELECT id, username, email,nickname FROM users WHERE id = ${req.user.id}`;
    db.query(sql, (err, result) => {
        if (err) return res.cc("查询出错")
        if (result.length === 0) return res.cc("用户不存在")

        res.send(result[0])
    })
}



exports.updateUserInfo = (req, res) => {
    let {  nickname, email, username } = req.body;
    let sql = `UPDATE users SET nickname=?, email=?, username=? WHERE id=?`;
    db.query(sql, [nickname, email, username, req.user.id], (err, result) => {
        if (err) return res.cc(err)
        console.log('更新成功', result)
        if (result.affectedRows === 0) return res.cc("用户不存在")
        res.send({ code: 0, msg: '更新成功' })
    })
}


const bcryptjs = require('bcryptjs');
exports.resetPwd = (req, res) => {
    let { oldPassword, newPassword } = req.body;
    console.log( req.user)
    const sql = "select password from users where id=?"
    db.query(sql, [req.user.id], (err, result) => {
        if (err) return res.cc(err)
        if (result.length === 0) return res.cc("用户不存在")
        let dbPassword = result[0].password;
        if (!bcryptjs.compareSync(oldPassword, dbPassword)) return res.cc("旧密码错误")

        let nPwd = bcryptjs.hashSync(newPassword, 10);
        let updatePwdSql = "update users set password=? where id=?";

        db.query(updatePwdSql, [nPwd, id], (err, result) => {
            if (err) return res.cc(err)
            if (result.affectedRows === 0) return res.cc("用户不存在")
            res.send({ code: 0, msg: "密码修改成功" })
        })
    })

}